package com.liveneo.system.base.utils;

import com.liveneo.adapter.base.entity.ZteResultRecords;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * Xml和对象转换工具
 * 
 * @author fucy
 *
 */
public class XmlUtils {
    public static XStream getStream(){  
        return new XStream();  
    }  
	
	/**
	 * 对象转换为xml字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static String toXml(Object obj){
		XStream xstream = new XStream();
		
		return xstream.toXML(obj);
	}
	
	/**
	 * xml转换为对象
	 * 
	 * @param xml
	 * @param type
	 * @return
	 */
	public static <T> T toObject(String xml, Class<T> type){
		XStream xstream = new XStream();
		
		xstream.processAnnotations(type);
		xstream.ignoreUnknownElements();
		
		Object obj = xstream.fromXML(xml);
		
		return type.cast(obj);
	}
	
	public static <T> T fromXML(String xml, Class<T> clazz){  
        XStream stream= XmlUtils.getStream();  
        stream.processAnnotations(clazz); 
        stream.ignoreUnknownElements();
        Object obj= stream.fromXML(xml);  
        try{  
            return clazz.cast(obj);  
        }catch(ClassCastException e){  
            return null;  
        }  
    }
	
	public static ZteResultRecords toZTEObject(String xml){
        XStream xstream = new XStream(new DomDriver());
        xstream.autodetectAnnotations(true);
        xstream.alias("records",ZteResultRecords.class);
        ZteResultRecords records =  (ZteResultRecords) xstream.fromXML(xml);
        return records;
    }
	
}
